<template>
  <div class="service-type-management-edit">
    <el-card>
      <div class="card-header">
        <span>编辑服务类型</span>
      </div>
      
      <el-form v-if="serviceTypeInfo" :model="serviceTypeForm" :rules="rules" ref="serviceTypeForm" label-width="120px">
        <el-form-item label="类型名称" prop="typeName">
          <el-input v-model="serviceTypeForm.typeName" placeholder="请输入服务类型名称" maxlength="100"></el-input>
        </el-form-item>
        
        <el-form-item label="描述信息" prop="description">
          <el-input v-model="serviceTypeForm.description" placeholder="请输入描述信息" type="textarea" maxlength="500" show-word-limit></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
      
      <div v-else class="loading-container">
        <el-loading v-loading="true" element-loading-text="加载中..." style="min-height: 200px;"></el-loading>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'ServiceTypeManagementEdit',
  data() {
    return {
      serviceTypeInfo: null,
      serviceTypeForm: {
        id: '',
        typeName: '',
        description: ''
      },
      rules: {
        typeName: [
          { required: true, message: '请输入服务类型名称', trigger: 'blur' },
          { max: 100, message: '服务类型名称不能超过100个字符', trigger: 'blur' }
        ],
        description: [
          { max: 500, message: '描述信息不能超过500个字符', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    const typeId = this.$route.query.id;
    if (typeId) {
      this.loadServiceTypeInfo(typeId);
    } else {
      this.$message.error('服务类型ID不能为空');
      this.$router.push('/service-type-management');
    }
  },
  methods: {
    loadServiceTypeInfo(typeId) {
      this.$api.serviceTypeApi.getById(typeId)
        .then(res => {
          const data = res && res.data || null;
          if (data) {
            this.serviceTypeInfo = data;
            // 填充表单数据
            this.serviceTypeForm = {
              id: this.serviceTypeInfo.id,
              typeName: this.serviceTypeInfo.typeName,
              description: this.serviceTypeInfo.description || ''
            };
          } else {
            this.$message.error('获取服务类型信息失败');
            this.$router.push('/service-type-management');
          }
        })
        .catch(error => {
          console.error('获取服务类型信息失败:', error);
          this.$message.error('获取服务类型信息失败: ' + error.message);
          this.$router.push('/service-type-management');
        });
    },
    
    handleSubmit() {
      this.$refs.serviceTypeForm.validate((valid) => {
        if (valid) {
          // 检查服务类型名称是否已存在（排除当前记录）
          this.$api.serviceTypeApi.getAllList()
            .then(res => {
              const serviceTypes = res && res.data || [];
              const exists = serviceTypes.some(type => 
                type.typeName === this.serviceTypeForm.typeName && 
                type.id !== this.serviceTypeForm.id
              );
              
              if (exists) {
                this.$message.error('服务类型名称已存在');
                return;
              }
              
              // 提交表单
              this.$api.serviceTypeApi.update(this.serviceTypeForm.id, this.serviceTypeForm)
                .then(() => {
                  this.$message.success('服务类型更新成功');
                  this.$router.push('/service-type-management');
                })
                .catch(error => {
                  console.error('更新服务类型失败:', error);
                  this.$message.error('更新服务类型失败: ' + error.message);
                });
            })
            .catch(error => {
              console.error('检查服务类型名称失败:', error);
              // 继续提交，让后端进行验证
              this.$api.serviceTypeApi.update(this.serviceTypeForm.id, this.serviceTypeForm)
                .then(() => {
                  this.$message.success('服务类型更新成功');
                  this.$router.push('/service-type-management');
                })
                .catch(error => {
                  console.error('更新服务类型失败:', error);
                  this.$message.error('更新服务类型失败: ' + error.message);
                });
            });
        }
      });
    },
    
    handleCancel() {
      this.$router.push('/service-type-management');
    }
  }
};
</script>

<style scoped>
.service-type-management-edit {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.loading-container {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>